/*
 * @Author: your name
 * @Date: 2021-03-03 15:55:10
 * @LastEditTime: 2021-03-03 15:57:39
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \xlsx-demo\src\index.ts
 */
import XLSX from "xlsx";

const s2ab = (s: any) => {
  if (typeof ArrayBuffer !== "undefined") {
    let buf = new ArrayBuffer(s.length);
    let view = new Uint8Array(buf);
    for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
  } else {
    let buf: any = new Array(s.length);
    for (let i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xff;
    return buf;
  }
};

const saveAs = (obj: any, fileName: string) => {
  var tmpa = document.createElement("a");
  tmpa.download = fileName || "下载";
  const href = URL.createObjectURL(obj); //绑定a标签
  tmpa.href = href;

  tmpa.click(); //模拟点击实现下载
  setTimeout(function () {
    //延时释放
    URL.revokeObjectURL(href); //用URL.revokeObjectURL()来释放这个object URL
  }, 100);
};

const downloadTmplate = () => {
  //待展示的数据，可能是从后台返回的json数据或者是自己定义的object
  const data: any[] = [{"H1" : 123},{"H2": 456}];
  //展示的顺序，把data中对象的属性按照你想要的顺序排放就可以了，我这里把id移到了第一列展示
  const header = ["H1", "H2"];
  let workbook = XLSX.utils.json_to_sheet(data, { header: header });
  const wopts: any = { bookType: "xlsx", bookSST: false, type: "binary" }; //这里的数据是用来定义导出的格式类型
  let wb: any = { SheetNames: ["Sheet1"], Sheets: {}, Props: {} };
  wb.Sheets["Sheet1"] = workbook;
  saveAs(
    new Blob([s2ab(XLSX.write(wb, wopts))], {
      type: "application/octet-stream",
    }),
    `批量查询导入模板.xlsx`
  );
};
